package com.example.livedata.fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import com.example.livedata.R;
import com.example.livedata.ViewModel.SeekBarViewModel;

public class FirstBarFragment extends Fragment implements SeekBar.OnSeekBarChangeListener {


    private SeekBarViewModel viewModel;
    private SeekBar seekbar;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //获取布局
        View view = inflater.inflate(R.layout.fragment_first_bar, container, false);
        //获取seekbar组件
        seekbar = view.findViewById(R.id.seekBar);
        //创建viewModel对象
        viewModel = new ViewModelProvider(getActivity() , new ViewModelProvider.AndroidViewModelFactory(getActivity().getApplication())).get(SeekBarViewModel.class);
        //设置seekbar的初始值
        seekbar.setProgress(viewModel.getProgress().getValue());
        //添加观察器只要viewModel的值发生变化 就执行该方法
        viewModel.getProgress().observe(getActivity(), integer -> {
            seekbar.setProgress(integer);
        });
        seekbar.setOnSeekBarChangeListener(this);
        return view;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        viewModel.getProgress().setValue(i);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}